<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xqts="http://www.w3.org/2005/02/query-test-XQTSCatalog"
                exclude-result-prefixes="#all"
                version="2.0">

   <!-- Must end with a '/'. -->
   <xsl:param name="output-dir" required="yes"/>
   
   <xsl:template match="/">
      <xsl:if test="not(ends-with($output-dir, '/'))">
         <xsl:message terminate="yes">
            <xsl:text>$output-dir does not terminate with a slash! (</xsl:text>
            <xsl:value-of select="$output-dir"/>
            <xsl:text>)</xsl:text>
         </xsl:message>
      </xsl:if>
      <xsl:apply-templates/>
   </xsl:template>

   <xsl:template match="node()">
      <xsl:copy>
         <xsl:copy-of select="@*"/>
         <xsl:apply-templates select="node()"/>
      </xsl:copy>
      <xsl:apply-templates select="xqts:test-group|xqts:test-case" mode="recurse"/>
   </xsl:template>

   <xsl:template match="xqts:test-group|xqts:test-case">
      <xsl:copy>
         <xsl:copy-of select="@name"/>
      </xsl:copy>
      <xsl:apply-templates select="xqts:test-case" mode="recurse"/>
   </xsl:template>

   <xsl:template match="xqts:test-group|xqts:test-case" mode="recurse">
      <xsl:variable name="dir" select="if ( self::xqts:test-group ) then 'groups' else 'cases'"/>
      <xsl:result-document href="{ resolve-uri(concat(@name, '.xml'), concat($output-dir, $dir, '/')) }">
         <xsl:apply-templates select="." mode="copy"/>
      </xsl:result-document>
      <xsl:apply-templates select="xqts:test-group" mode="recurse"/>
   </xsl:template>

   <xsl:template match="node()" mode="copy">
      <xsl:copy>
         <xsl:copy-of select="@*"/>
         <xsl:if test="exists(parent::xqts:test-group)">
            <xsl:attribute name="parent-group" select="../@name"/>
         </xsl:if>
         <xsl:apply-templates select="node()"/>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>
